//
//  SafariViewController.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/6/6.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "SafariViewController.h"
#import "TextbookChapterDetailModel.h"
#import "TextbookQuestionsModel.h"
#import "HomeRequest.h"
@interface SafariViewController ()<IFlyDetectionDelegate>
{
    NSString *url;
    NSString *wordId;
}
@property (nonatomic,strong) IFlyDetection *detection;//评测对象
@end

@implementation SafariViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"back"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"goWordsPK"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"gotoHearSayPage"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"startRecord"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"stopRecord"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileName = [NSString stringWithFormat:@"%@",lApp.useModel.username];
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 因此这里要记得移除handlers
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"back"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goWordsPK"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"gotoHearSayPage"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"startRecord"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"stopRecord"];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self stop];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.webView];
    [self reloadWebviewWithUrl:url];
    self.detection.delegate = self;
    [self.detection evalutType:0];
    [self.detection evalutSource:1];
    [self.detection evalutLanguage:1];
}
- (void)setParaObject:(NSObject *)paraObject
{
    url = (NSString *)paraObject;
}
- (void)wb_userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"back"]) {
        [self back];
    }
    
    if ([message.name isEqualToString:@"startRecord"]) {
        NSDictionary *dic = message.body;
        wordId = dic[@"Id"];
        [self recordWithText:dic[@"words"]];
    }
    
    if ([message.name isEqualToString:@"stopRecord"]) {
        [self stop];
    }
    
    if ([message.name isEqualToString:@"goWordsPK"]) {
        [self pushToViewControllerWithClassName:@"PkViewController" animated:YES];
    }
    
//    if ([message.name isEqualToString:@"gotoHearSayPage"]) {
//        NSDictionary *dic = message.body;
//        ListenTestViewController *vc = [[ListenTestViewController alloc] init];
//        HsrModel *hr = [HsrModel new];
//        hr.resourceName = dic[@"resourceName"];
//        hr.versionId = dic[@"versionId"];
//        vc.mission_id = [NSString stringWithFormat:@"%@",dic[@"mission_id"]];
//        vc.model = hr;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    
}
-(void)postToh5WithDic:(NSDictionary *)dic
{
    NSString *injectionJSString = [NSString stringWithFormat:@"recordFinishCallback(%@)",[dic modelToJSONString]];
    [self.webView evaluateJavaScript:injectionJSString completionHandler:nil];
}
#pragma mark - IFlyDetectionDelegate
- (void)evaluting:(IFlyDetection *)ifyldetection result:(NSString *)result {
    
    //评测分数
//    CGFloat totalScore = 0;//总分
//    CGFloat standardscore = 0;//
//    CGFloat integrityscore = 0;//完整度分
//    CGFloat fluencyscore = 0;//流畅度分
//    CGFloat accuracyscore = 0;//准确度分
//
    NSArray<NSString*> *words = [result componentsSeparatedByString:@"\n"];
    
    NSString *searchWord = @"Total Score：";
    NSString *searchWord2 = @"Standard Score：";
    NSString *searchWord3 = @"Integrity Score：";
    NSString *searchWord4 = @"Fluency Score：";
    NSString *searchWord5 = @"Accuracy Acore：";
    for (NSString *obj in words) {
        
        if ([obj containsString:searchWord]) {
            ifyldetection.question.totalScore = [[obj substringFromIndex:searchWord.length] floatValue];
        }
        if ([obj containsString:searchWord2]) {
            ifyldetection.question.standardscore = [[obj substringFromIndex:searchWord2.length] floatValue];
        }
        if ([obj containsString:searchWord3]) {
            ifyldetection.question.integrityscore = [[obj substringFromIndex:searchWord3.length] floatValue];
        }
        if ([obj containsString:searchWord4]) {
            ifyldetection.question.fluencyscore = [[obj substringFromIndex:searchWord4.length] floatValue];
        }
        if ([obj containsString:searchWord5]) {
            ifyldetection.question.accuracyscore = [[obj substringFromIndex:searchWord5.length] floatValue];
        }
        ifyldetection.question.questionRefSorce = ifyldetection.question.totalScore/100.00*ifyldetection.question.score;
      
        DebugLog(@"========= %@ == ",obj);
    }
    
   // DebugLog(@"评测结果: %@ == %f",result,totalScore);
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:ifyldetection.question.recordPath]) {
        [HomeRequest upLoadAudioWithPath:ifyldetection.question.recordPath result:^(NSDictionary *url) {
            if (!IsStrEmpty(url[@"fullurl"])) {
                ifyldetection.question.recordUrl = url[@"fullurl"];
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:url];
                [dic setObject:@(ifyldetection.question.accuracyscore) forKey:@"accuracy_score"];
                
                [dic setObject:@(ifyldetection.question.fluencyscore) forKey:@"fluency_score"];
                [dic setObject:@(ifyldetection.question.integrityscore) forKey:@"integrity_score"];
                [dic setObject:@(ifyldetection.question.totalScore) forKey:@"total_score"];
                if (self->wordId.length > 0) {
                    [dic setObject:self->wordId forKey:@"id"];
                }
                [self postToh5WithDic:dic];
            }
        }];
    }
    
}

- (void)onCompleted:(IFlySpeechError *)errorCode { 
    
}

- (void)recordWithText:(NSString *)text{
    [self stop];
    
    HSQuestion *question = [HSQuestion new];
    question.answer = text;
    question.versionId = wordId;
    //开始录音
    void(^StartSpeakingVoice)(void) = ^() {
        
        self.detection.question = question;
        
        //        if (self.showQuestion.type == 6) {
        //            NSString *str = self.showQuestion.trunk.body;
        //            NSString *quest = [str componentsSeparatedByString:@"\n"].firstObject;
        //            NSString *choice = [str componentsSeparatedByString:@"\n"].lastObject;
        //            choice = [choice stringByReplacingOccurrencesOfString:@"(" withString:@""];
        //            choice = [choice stringByReplacingOccurrencesOfString:@")" withString:@""];
        //            NSArray *wrd = [choice componentsSeparatedByString:@"/"];
        //            choice = @"";
        //            for (int i = 0; i < wrd.count; i++) {
        //                choice = [NSString stringWithFormat:@"%@%d.%@\n",choice,i+1,wrd[i]];
        //            }
        //            choice =[NSString stringWithFormat:@"%@[keywords]\n%@[question]%@",choice,self.detection.question.answer,quest];
        //            [self.detection startEvalutingWord:choice];
        //        }else{
        //            [self.detection startEvalutingWord:self.detection.question.answer];
        //        }
        [self.detection startEvalutingWord:self.detection.question.answer];
        //[NSString stringWithFormat:@"%@",@""]
        
    };
    
    //检测是否授权麦克风
    void(^CheckOutAuthorization)(void) = ^() {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            //第一次询问用户是否进行授权
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    StartSpeakingVoice();
                }
            }];
        }
        else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
            //            NSString *message = @"\n麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能";
            //            [[UIViewController ge] alertViewTitle:@"麦克风权限未开启" message:message left:@"确定" leftBlock:^{
            //
            //            } right:@"前往" rightBlock:^{
            //                //跳入当前App设置界面
            //                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            //            }];
        }
        else{// 已授权
            StartSpeakingVoice();
        }
    };
    
    CheckOutAuthorization();
    
}
- (void)stop
{
    
    [self.detection stop];
    
}
- (IFlyDetection *)detection {
    if (!_detection) {
        _detection = [[IFlyDetection alloc] init];
        _detection.delegate = self;
    }
    return _detection;
}
-(void)back
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



@end
